package com.atguigu.lease.web.admin.schedule;

import com.atguigu.lease.model.entity.LeaseAgreement;
import com.atguigu.lease.model.enums.LeaseStatus;
import com.atguigu.lease.web.admin.service.LeaseAgreementService;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @Author GQS @Date 2024/9/3/15:39 @Description
 */
@Component
public class ScheduledTasks {
    @Autowired
    private LeaseAgreementService leaseAgreementService;

    /**
     * 每日定时检查租赁协议状态并更新
     * 本方法通过定时任务每日凌晨自动执行，将租赁结束日期在当日及之前的
     * 已签署和正在撤租状态的租赁协议状态更新为已过期
     */
    @Scheduled(cron = "0 0 0 * * *")
    public void checkLeaseStatus() {

        // 构建更新条件
        LambdaUpdateWrapper<LeaseAgreement> updateWrapper = new LambdaUpdateWrapper<>();
        Date now = new Date();

        // 条件1：租赁结束日期在当日及之前的协议
        updateWrapper.le(LeaseAgreement::getLeaseEndDate, now);

        // 条件2：协议状态为已签署或正在撤租
        updateWrapper.in(LeaseAgreement::getStatus, LeaseStatus.SIGNED, LeaseStatus.WITHDRAWING);

        // 设置更新后的状态为已过期
        updateWrapper.set(LeaseAgreement::getStatus, LeaseStatus.EXPIRED);

        // 执行更新操作
        leaseAgreementService.update(updateWrapper);
    }
    }

